<?php

App::uses('CrudController', 'Controller');

class WorkstationsController extends CrudController
{
    public $_model = 'Workstation';

    public function admin($lineId, $areaId, $moeId)
    {
        $this->request->allowMethod('get');
        $this->loadModel('Area');
        $this->loadModel('Moe');
        $this->loadModel('Line');
        $appBosch = new stdClass();
        $appBosch->lineId = $lineId;
        $appBosch->areaId = $areaId;
        $appBosch->moeId = $moeId;
        $description = $this->getDescription($lineId, $areaId, $moeId);
        $this->set('appBosch', $appBosch);
        $this->set('title', __('Operaciones'));
        $this->set('description', $description);
    }

    private function getDescription($lineId, $areaId, $moeId)
    {
        $this->Moe->id = $moeId;
        $moe = $this->Moe->read();
        $this->Area->id = $areaId;
        $area = $this->Area->read();
        $this->Line->id = $lineId;
        $line = $this->Line->read();
        $parts = array(
            $moe['Moe']['name'],
            $area['Area']['name'],
            $line['Line']['name'],
        );
        return implode(' - ', $parts);
    }

    public function uploadFiles()
    {
        $upload_dir = TMP;
        $path = $upload_dir . DS . 'Workstations';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
            $sub_path = $path . DS . 'certifications';
            mkdir($sub_path, 0777, true);
        }
        $path .= DS . 'certifications';
        $name = 'file.img';
        $file = $_FILES['img'];
        move_uploaded_file($file['tmp_name'], $path . DS . $file['name']);
        $this->Session->write($name . '.name', $file['name']);
        $this->Session->write($name . '.path', $path);
        $succes = $path . DS . $file['name'];
        $this->set(array('succes' => $succes, '_serialize' => 'succes'));
        $this->viewClass = 'Json';
    }

    public function deletedUploaded()
    {
        $upload_dir = TMP;
        $path = $upload_dir . DS . 'Workstations';
        if ($this->Session->check('file.img')) {
            $file = $this->Session->read('file.img');
            unlink($path . DS . 'certifications' . DS . $file['name']);
            $this->Session->delete("file.img");
        }
        $succes = $path . DS . $file['name'];
        $this->set(array('succes' => $succes, '_serialize' => 'succes'));
        $this->viewClass = 'Json';
    }

    public function createImages()
    {
        $workstations = $this->Workstation->getEnabled();
        foreach ($workstations as $w) {
            $this->createImage($w['id'], $w['description'], 200, 50, $w['optional']);
            $this->createImage2($w['id'], $w['description'], 250, 75, $w['optional']);
        }
    }

    private function createImage($id, $text, $width, $height, $optional)
    {
        $image = imagecreatetruecolor($width, $height);
        imagesavealpha($image, true);
        $textColor = imagecolorallocate($image, 81, 89, 103);
        $backgroundColor = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 1, 1, $backgroundColor);
        $fontSize = 11;
        $fontPath = CSS . 'vendors' . DS . 'kendo' . DS . 'fonts' . DS . 'DejaVu' . DS . 'DejaVuSans.ttf';
        if ($optional == 1) {
            $fontPath = CSS . 'vendors' . DS . 'kendo' . DS . 'fonts' . DS . 'DejaVu' . DS . 'DejaVuSans-Oblique.ttf';
            $textColor = imagecolorallocate($image, 120, 120, 120);
        }
        /**
         * No puede exceder el 90% para que conserve un margen
         */
        $txtMaxWidth = intval(0.95 * $width);
        if ($text != '') {
            if ($optional === true) {
                $text .= ' [o]'; // Indica que es una Operación opcional
            }
            // Dividimos el texto en palabras, la separacion se hace por espacios.
            $words = preg_split("/[\s]+/", $text);
            $rows = array(); //Almacenana el texto convertido en renglones
            $row = array(); // Un renglon
            array_walk($words, function ($word) use (&$rows, &$row, $fontSize, $txtMaxWidth, $fontPath) {
                /**
                 * Agregamos una palabra al renglon y checamos si cabe en el contenedor
                 */
                $row[] = $word;
                $text = implode(' ', $row);
                $p = imagettfbbox($fontSize, 0, $fontPath, $text);
                $txtWidth = $p[2] - $p[0];
                /**
                 * El texto ya no cabe en el contenedor
                 */
                if ($txtWidth >= $txtMaxWidth) {
                    /**
                     * Eliminamos la ultima palabra del renglon porque con esa
                     * palabra el renglon se sale del contenedor
                     */
                    $lastWord = array_pop($row);
                    /**
                     * La convertimos en cadena
                     */
                    $rows[] = implode(' ', $row);
                    /**
                     * La palabra que provoco que se saliera del contenedor se
                     * asigna como la primera palabra del proximo renglon
                     */
                    $row = array($lastWord);
                }
            });
            /**
             * El ultimo renglon se agrega al arreglo de renglones
             */
            $rows[] = implode(' ', $row);
            $textInRows = implode("\n", $rows);
            $p = imagettfbbox($fontSize, 0, $fontPath, $textInRows);
            $txt_height = $p[1] - $p[7]; // just in case you need it
            $heightRow = $txt_height / count($rows);
            $y = $heightRow + (($height - $txt_height) / 2) - 2 * count($rows);
            imagettftext($image, $fontSize, 0, 10, $y, $textColor, $fontPath, $textInRows);
        }
        /* @var $imageRotate Resource */
        $imageRotate = imagerotate($image, 90, $backgroundColor);
        imagecolortransparent($imageRotate, $backgroundColor);
        /**
         * Generamos un archivo con la imagen que se identifique por su id
         */
        imagepng($imageRotate, TMP . 'Workstations' . DS . $id . '.png');
        imagedestroy($image);
    }

    private function createImage2($id, $text, $width, $height, $optional)
    {
        $image = imagecreatetruecolor($width, $height);
        imagesavealpha($image, true);
        $textColor = imagecolorallocate($image, 81, 89, 103);
        $backgroundColor = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 1, 1, $backgroundColor);
        $fontSize = 20;
        $fontPath = CSS . 'vendors' . DS . 'kendo' . DS . 'fonts' . DS . 'DejaVu' . DS . 'DejaVuSans.ttf';
        if ($optional == 1) {
            $fontPath = CSS . 'vendors' . DS . 'kendo' . DS . 'fonts' . DS . 'DejaVu' . DS . 'DejaVuSans-Oblique.ttf';
            $textColor = imagecolorallocate($image, 120, 120, 120);
        }
        /**
         * No puede exceder el 90% para que conserve un margen
         */
        $txtMaxWidth = intval(0.95 * $width);
        if ($text != '') {
            if ($optional === true) {
                $text .= ' [o]'; // Indica que es una Operación opcional
            }
            // Dividimos el texto en palabras, la separacion se hace por espacios.
            $words = preg_split("/[\s]+/", $text);
            $rows = array(); //Almacenana el texto convertido en renglones
            $row = array(); // Un renglon
            array_walk($words, function ($word) use (&$rows, &$row, $fontSize, $txtMaxWidth, $fontPath) {
                /**
                 * Agregamos una palabra al renglon y checamos si cabe en el contenedor
                 */
                $row[] = $word;
                $text = implode(' ', $row);
                $p = imagettfbbox($fontSize, 0, $fontPath, $text);
                $txtWidth = $p[2] - $p[0];
                /**
                 * El texto ya no cabe en el contenedor
                 */
                if ($txtWidth >= $txtMaxWidth) {
                    /**
                     * Eliminamos la ultima palabra del renglon porque con esa
                     * palabra el renglon se sale del contenedor
                     */
                    $lastWord = array_pop($row);
                    /**
                     * La convertimos en cadena
                     */
                    $rows[] = implode(' ', $row);
                    /**
                     * La palabra que provoco que se saliera del contenedor se
                     * asigna como la primera palabra del proximo renglon
                     */
                    $row = array($lastWord);
                }
            });
            /**
             * El ultimo renglon se agrega al arreglo de renglones
             */
            $rows[] = implode(' ', $row);
            $textInRows = implode("\n", $rows);
            $p = imagettfbbox($fontSize, 0, $fontPath, $textInRows);
            $txt_height = $p[1] - $p[7]; // just in case you need it
            $heightRow = $txt_height / count($rows);
            $y = $heightRow + (($height - $txt_height) / 2) - 2 * count($rows);
            imagettftext($image, $fontSize, 0, 10, $y, $textColor, $fontPath, $textInRows);
        }
        /* @var $imageRotate Resource */
        $imageRotate = imagerotate($image, 90, $backgroundColor);
        imagecolortransparent($imageRotate, $backgroundColor);
        /**
         * Generamos un archivo con la imagen que se identifique por su id
         */
        imagepng($imageRotate, TMP . 'Workstations' . DS . $id . 'B.png');
        imagedestroy($image);
    }

    public function getWorkstationsByLine($all = null)
    {
        $this->request->allowMethod('get');
        $areaId = $this->request->query['filter']['filters'][0]['value'];
        $m = $this->_model;
        $records = $this->$m->getEnabledByLineBasic($areaId);
        if ($all != null) {
            array_unshift($records, array("text" => 'Todas', "value" => '0'));
        }
        $this->set(array('records' => $records, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    public function getWorkstationsForCombo()
    {
        $this->request->allowMethod('get');
        $m = $this->_model;
        $records = $this->$m->getEnabledWithHierarchy();
        array_unshift($records, array("text" => 'Todas', "value" => '0'));
        $this->set(array('records' => $records, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    protected function getRecords($param)
    {
        $m = $this->_model;
        $records = $this->$m->getEnabledByLine($param);
        foreach ($records as &$record) {
            $record['optional'] = $record['optional'] === '1';
        }
        return $records;
    }

    protected function c($model)
    {
        $vigenciaProccess = (int)$model->vigenciaProccess;
        $maxProccess = (int)$model->maxProccess;
        if ($maxProccess < $vigenciaProccess) {
            $maxProccess = $vigenciaProccess;
        }
        return array(
            'line_id' => trim($model->line_id),
            'name' => (int)$model->name,
            'description' => mb_strtoupper(trim($model->description)),
            'life' => (int)$model->vigenciaCertification * 365,
            'vigenciaCertification' => (int)$model->vigenciaCertification,
            'vigenciaProccess' => (int)$model->vigenciaProccess,
            'days' => $vigenciaProccess * 7,
            'max_days' => $maxProccess * 7,
            'maxProccess' => $maxProccess,
            'notification_end' => (int)$model->notification_end,
            'notification_life' => (int)$model->notification_life,
            'optional' => $model->optional === true ? Workstation::OPTIONAL_YES : Workstation::OPTIONAL_NO,
            'img' => $model->img,
            'lock_days' => (int)$model->lock_days
        );
    }

    protected function u($model)
    {
        $vigenciaProccess = (int)$model->vigenciaProccess;
        $maxProccess = (int)$model->maxProccess;
        if ($maxProccess < $vigenciaProccess) {
            $maxProccess = $vigenciaProccess;
        }
        return array(
            'name' => (int)$model->name,
            'description' => mb_strtoupper(trim($model->description)),
            'life' => (int)$model->vigenciaCertification * 365,
            'vigenciaCertification' => (int)$model->vigenciaCertification,
            'days' => $vigenciaProccess * 7,
            'max_days' => $maxProccess * 7,
            'maxProccess' => $maxProccess,
            'vigenciaProccess' => (int)$model->vigenciaProccess,
            'notification_end' => (int)$model->notification_end,
            'notification_life' => (int)$model->notification_life,
            'optional' => $model->optional === true ? Workstation::OPTIONAL_YES : Workstation::OPTIONAL_NO,
            'img' => $model->img,
            'lock_days' => (int)$model->lock_days
        );
    }

    protected function afterCreate(&$newRecord)
    {
        $text = $newRecord['description'];
        $this->createImage($newRecord['id'], $text, 150, 70, $newRecord['optional']);

        $m = $this->_model;
        $this->$m->id = $newRecord['id'];
        $files = array();
        if ($this->Session->check('file.img')) {
            $file = $this->Session->read('file.img');
            $filenameParts = explode('.', $file['name']);
            $ext = $filenameParts[1];
            $newName = $file['path'] . DS . $newRecord['id'] . '.' . $ext;
            rename($file['path'] . DS . $file['name'], $newName);
            $route = '/PHP_TEMP/Workstations/certifications/' . $newRecord['id'] . '.' . $ext;
            $files['image'] = $route;
            $newRecord['img'] = $route;
            $this->Session->delete("file.img");
            $this->$m->save($files);
        }
        return true;
    }

    protected function afterUpdate($id, &$updatedRecord)
    {
        $text = $updatedRecord['description'];
        $this->createImage($id, $text, 150, 70, $updatedRecord['optional']);

        $m = $this->_model;
        $this->$m->id = $id;
        $reg = $this->$m->read();
        $files = array();
        if ($this->Session->check('file.img')) {
            if ($reg['Workstation']['image'] != null) {
                $parts = explode('/', $reg['Workstation']['image']);
                $fileName = array_pop($parts);
                $fileName = explode('.', $fileName);
                if (mb_strlen($fileName[0]) == 36) {
                    unlink(WWW_ROOT . str_replace(Router::url('/', true), '', $reg['Workstation']['image']));
                }
            }
            $file = $this->Session->read('file.img');
            $filenameParts = explode('.', $file['name']);
            $ext = $filenameParts[1];
            $newName = $file['path'] . DS . $id . '.' . $ext;
            rename($file['path'] . DS . $file['name'], $newName);
            $route = '/PHP_TEMP/Workstations/certifications/' . $id . '.' . $ext;
            $files['image'] = $route;
            $updatedRecord['img'] = $route;
            $this->Session->delete("file.img");
            $this->$m->save($files);
        }
        return true;
    }
}
